package com.shirley.reactive.ws.server.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ReactiveWsServerHandler implements WebSocketHandler {

    private static AtomicInteger msgCount = new AtomicInteger(0);

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        Flux<WebSocketMessage> output = session.receive()
                .map(WebSocketMessage::getPayloadAsText)
                .doOnNext(msg -> {
                    log.info("Get message from client: {}", msg);
                }).map(input -> session.textMessage("This is the " + msgCount.incrementAndGet() + " message from server."));
        return session.send(output);
    }
}
